package cn.itcast.bos.web.base.action;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import org.apache.commons.io.FileUtils;
import org.apache.poi.ss.formula.functions.T;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.junit.Test;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

import static org.aspectj.weaver.tools.cache.SimpleCacheFactory.path;

/**
 * Created by Administrator on 2017/7/21/021.
 */
@ParentPackage("json-default")
@Namespace("/")
@Controller
@Scope("prototype")
public class ImageAction extends ActionSupport {

    //文件上传固定写法
    private File imgFile;
    private String imgFileFileName;
    private String imgFileContentType;

    public File getImgFile() {
        return imgFile;
    }

    public void setImgFile(File imgFile) {
        this.imgFile = imgFile;
    }

    public String getImgFileFileName() {
        return imgFileFileName;
    }

    public void setImgFileFileName(String imgFileFileName) {
        this.imgFileFileName = imgFileFileName;
    }

    public String getImgFileContentType() {
        return imgFileContentType;
    }

    public void setImgFileContentType(String imgFileContentType) {
        this.imgFileContentType = imgFileContentType;
    }

    @Action(value = "/img_upload", results = {
            @Result(name = "success", type = "json")})
    public String uploadImage() throws IOException {
        UUID uuid = UUID.randomUUID();
        //查询图片类型
        String ext = imgFileFileName.substring(imgFileFileName.lastIndexOf("."));
        String randomFileName = uuid + ext;
        String savepath = ServletActionContext.getServletContext().getRealPath("/upload");
        String saveurl = ServletActionContext.getServletContext().getContextPath() + "/upload";
        //复制文件到路径
        FileUtils.copyFile(imgFile, new File(savepath + "/" + randomFileName));
        //回显错误和成功信息
        Map<String, Object> result = new HashMap<>();
        result.put("error", 0);
        result.put("url", saveurl + "/" + randomFileName);
        ActionContext.getContext().getValueStack().push(result);
        return SUCCESS;
    }

    @Action(value = "/manage_img", results = {
            @Result(name = "success", type = "json"),
            @Result(name = "input", type = "redirect", location = "../pages/take_delivery/promotion_add.html")
    })
    public String manageImage() {

        String path = ServletActionContext.getRequest().getParameter("path") != null ?
                ServletActionContext.getRequest().getParameter("path") : "";
        String rootPath = ServletActionContext.getServletContext().getRealPath("/upload/");
        String rootUrl = ServletActionContext.getServletContext().getContextPath() + "/upload/";
        String currentPath = rootPath + path;
        String currentUrl = rootUrl + path;
        String currentDirPath = path;
        String[] fileTypes = new String[]{"gif", "jpg", "jpeg", "png", "bmp"};
        File currentPathFile = new File(currentPath);

        String dirName = ServletActionContext.getRequest().getParameter("dir");
        if (dirName != null) {
            if (!Arrays.<String>asList(new String[]{"image", "flash", "media", "file"}).contains(dirName)) {
                System.out.println("Invalid Directory name.");
                return INPUT;
            }
            rootPath += dirName + "/";
            rootUrl += dirName + "/";
            File saveDirFile = new File(rootPath);
            if (!saveDirFile.exists()) {
                saveDirFile.mkdirs();
            }
        }
        //遍历目录取的文件信息
        List<Hashtable> fileList = new ArrayList<>();
        if (currentPathFile.listFiles() != null) {
            for (File file : currentPathFile.listFiles()) {
                Hashtable<String, Object> hash = new Hashtable<>();
                String fileName = file.getName();
                if (file.isDirectory()) {
                    hash.put("is_dir", true);
                    hash.put("has_file", (file.listFiles() != null));
                    hash.put("filesize", 0L);
                    hash.put("is_photo", false);
                    hash.put("filetype", "");
                } else if (file.isFile()) {
                    String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                    hash.put("is_dir", false);
                    hash.put("has_file", false);
                    hash.put("filesize", file.length());
                    hash.put("is_photo", Arrays.<String>asList(fileTypes).contains(fileExt));
                    hash.put("filetype", fileExt);
                }
                hash.put("filename", fileName);
                hash.put("datetime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(file.lastModified()));
                fileList.add(hash);
            }
        }

        Map<String, Object> result = new HashMap<>();
        result.put("moveup_dir_path", "");
        result.put("current_dir_path", currentDirPath);
        result.put("current_url", currentUrl);
        result.put("total_count", fileList.size());
        result.put("file_list", fileList);

        ServletActionContext.getResponse().setContentType("application/json; charset=UTF-8");
        ActionContext.getContext().getValueStack().push(result);
        System.out.println(result.toString());
        return SUCCESS;
    }

}
